package com.kefu.chat.controller;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kefu.chat.model.ChatChannel;
import com.kefu.chat.service.ChatChannelService;
import com.kefu.chat.service.ChatWxMiniService;
import com.kefu.common.controller.AbstractBaseController;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import cn.hutool.core.util.StrUtil;
import me.chanjar.weixin.common.api.WxConsts;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@RestController
@RequestMapping("chat/wxmini/{appId}")
public class ChatWxMiniController extends AbstractBaseController {

    @Autowired
    private ChatWxMiniService chatWxMiniService;
    @Autowired
    private ChatChannelService chatChannelService;

    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appId, String signature, String timestamp, String nonce, String echostr) {
        logger.info("接收到来自微信小程序的认证消息：[{},{}, {}, {}, {}]", appId, signature, timestamp, nonce, echostr);
        ChatChannel channel = chatChannelService.getFromAppId(appId);
        if (channel == null) return null;
        WxMaService wxMaService = chatWxMiniService.getWxMaService(appId);
        if (wxMaService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return null;
    }

    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appId, @RequestBody String requestBody, String msg_signature, String encrypt_type, String signature, String timestamp, String nonce) {
        this.logger.info("接收微信小程序请求：[msg_signature=[{}], encrypt_type=[{}], signature=[{}]," +
                        " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                msg_signature, encrypt_type, signature, timestamp, nonce, requestBody);
        ChatChannel channel = chatChannelService.getFromAppId(appId);
        if (channel == null) return null;
        WxMaService wxMaService = chatWxMiniService.getWxMaService(appId);
        boolean isJson = Objects.equals(wxMaService.getWxMaConfig().getMsgDataFormat(),
                WxMaConstants.MsgDataFormat.JSON);
        WxMaMessage inMessage = null;
        if (StrUtil.isBlank(encrypt_type)) {
            // 明文传输的消息
            if (isJson) {
                inMessage = WxMaMessage.fromJson(requestBody);
            } else {
                //xml
                inMessage = WxMaMessage.fromXml(requestBody);
            }
        }
        if ("aes".equalsIgnoreCase(encrypt_type)) {
            // 是aes加密的消息
            if (isJson) {
                inMessage = WxMaMessage.fromEncryptedJson(requestBody, wxMaService.getWxMaConfig());
            } else {
                //xml
                inMessage = WxMaMessage.fromEncryptedXml(requestBody, wxMaService.getWxMaConfig(),
                        timestamp, nonce, msg_signature);
            }
        }
        logger.info("接收微信小程序请求解密:{},{}", appId, inMessage);
        if (inMessage != null) {
            if (inMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)) {
                chatWxMiniService.eventHandle(appId, inMessage);
            } else {
                chatWxMiniService.msgHandle(appId, inMessage);
            }
        }
        return "success";
    }

}

